import Boom from '@hapi/boom';
import Joi from 'joi';
import debugCheck from '@kuiper-helpers/debug-check';
import errorCodesBuilder from '../helpers/errorCodesBuilder';
import * as validation from '../../common/validation';
import joiOmit from '../helpers/joiOmit';
import findManyFilter from '../../common/validation/findManyFilter';

const errorCodes = errorCodesBuilder('新闻数据处理失败');

export const query = {
	tags: ['api', 'news'],
	description: '新闻列表',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },
	async handler(request, h) {
		const {
			server: {
				app: {
					model: { News },
				},
			},
		} = request;

		let news;
		try {
			news = await News.find();
		} catch (err) {
			const error = errorCodes['[13][新闻列表]新闻列表查询失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw Boom.badImplementation(error.rawMessage);
		}

		return h.response(news);
	},
};

export const pagination = {
	tags: ['api', 'news'],
	description: '新闻列表-分页查看',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },
	validate: {
		payload: Joi.object({
			page: Joi.number().default(1).description('当前页面'),
			perPage: Joi.number().default(10).description('每页条目数'),
			filter: findManyFilter.news.append({
				isPublished: Joi.boolean().description('是否已发布'),
				titleSearch: Joi.string().allow(null),
			}),
		}),
	},
	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { page, perPage, filter },
				} = request;

				return JSON.stringify({
					variables: { page, perPage, filter },
					query: `
						query($page: Int = 1, $perPage: Int = 10, $filter: FilterFindManyNewsInput, $sort: SortFindManyNewsInput = _ID_DESC){
							NewsPagination(page: $page, perPage: $perPage, filter: $filter, sort: $sort){
								count
								pageInfo {
									currentPage
									perPage
									pageCount
									itemCount
									hasNextPage
									hasPreviousPage
								}
								items {
									title
									author
									type
									link
									summary
									content
									isSendNotification
									isConsoleDisplay
									isHomepageDisplay
									isRecommendDisplay
									isPublished
									isDraft
									datetime
									image
									imgName
									_id
								}
							}
						}
					`,
				});
			},
		},
	},
};

export const createOne = {
	tags: ['api', 'news'],
	description: '创建新闻',
	payload: {
		maxBytes: 100485760,
	},
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },
	validate: {
		payload: validation.news,
	},

	async handler(request, h) {
		const {
			server: {
				app: {
					model: { News },
				},
			},
		} = request;

		const { payload: record } = request;

		let news;
		try {
			news = await new News(record).save();
		} catch (err) {
			const error = errorCodes['[13][新闻列表]新闻列表查询失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw Boom.badImplementation(error.rawMessage);
		}

		return h.response(news);
	},
};

export const removeMany = {
	tags: ['api', 'news'],
	description: '批量删除新闻',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },
	validate: {
		payload: Joi.object({
			ids: Joi.array().items(Joi.string()),
		}),
	},
	async handler(request, h) {
		const {
			server: {
				app: {
					model: { News },
				},
			},
		} = request;

		const {
			payload: { ids },
		} = request;

		try {
			await News.remove({ _id: { $in: ids } });
		} catch (err) {
			const error = errorCodes['[13][新闻列表]新闻批量删除失败'].from(err);
			request.log.error({ error }, error.rawMessage);
		}
		return h.response(ids);
	},
};

export const removeById = {
	tags: ['api', 'news'],
	description: '删除新闻',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },
	validate: {
		params: Joi.object({
			newsId: Joi.string(),
		}),
	},
	async handler(request, h) {
		const {
			server: {
				app: {
					model: { News },
				},
			},
		} = request;

		const {
			params: { newsId },
		} = request;

		let news;
		try {
			news = await News.remove({ _id: newsId });
		} catch (err) {
			const error = errorCodes['[13][新闻列表]根据id删除新闻失败'].from(err);
			request.log.error({ error }, error.rawMessage);
		}
		return h.response(news);
	},
};

export const updateById = {
	tags: ['api', 'news'],
	description: '更新新闻',
	payload: {
		maxBytes: 100485760,
	},
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },
	validate: {
		params: Joi.object({
			newsId: Joi.string().description('新闻ID'),
		}),
		payload: joiOmit(validation.news),
	},
	async handler(request, h) {
		const {
			server: {
				app: {
					model: { News },
				},
			},
		} = request;
		const {
			payload: record,
			params: { newsId },
		} = request;
		let updateNews;
		try {
			updateNews = await News.updateOne({ _id: newsId }, { $set: record });
		} catch (err) {
			const error = errorCodes['[13][新闻列表]新闻信息更新失败'].from(err);
			request.log.error({ error }, error.rawMessage);
		}
		return h.response(updateNews);
	},
};
